﻿using ExamRoomAllocationManagement.Services;
using Microsoft.AspNetCore.Mvc;
using System.Reflection.Metadata;
using System.Text.Json;
using System.Text.Json.Nodes;
using Xmu.ExamRoomAllocationManagement.Services;
using Xmu.Stores.Models;

namespace UserStores.Controllers
{
    [Route("/api/[controller]")]
    public class AllocationController : Controller
    {
        private AllocationService allocationService;
        private AutoAllocationService autoAllocationService;
        public AllocationController(AllocationService allocationService, AutoAllocationService autoAllocationService)
        {
            this.allocationService = allocationService;
            this.autoAllocationService = autoAllocationService;
        }


        [HttpGet]
        public IActionResult GetAllocations([FromQuery] int pageIndex, [FromQuery] int pageSize)
        {
            Console.WriteLine("*** this is controller *****");
            (object data, object pageNum, object msg) = allocationService.GetAllocations(pageIndex, pageSize);
            return Ok(new
            {
                msg,
                data,
                pageNum
            });
        }

        [HttpGet("status/{status}")]
        public IActionResult GetAllocationsByStatus(AllocationStatus status, [FromQuery] int pageIndex, [FromQuery] int pageSize)
        {
            (object data, object pageNum, object msg) = allocationService.GetAllocationsByStatus(status, pageIndex, pageSize);
            return Ok(new
            {
                msg,
                data,
                pageNum
            });
        }


        [HttpGet("all")]
        public IActionResult GetEveryAllocations()
        {
            (object data, object msg) = allocationService.GetEveryAllocations();
            return Ok(new
            {
                msg,
                data
            });
        }

        [HttpGet("{roomId}")]
        public IActionResult GetAllocationById(Guid roomId)
        {
            (object data, object msg) = allocationService.GetAllocation(roomId);
            return Ok(new
            {
                msg,
                data
            });
        }


        [HttpPut("autoAllocate")]
        public IActionResult AutoAllocate()
        {
            var (success, msg) = autoAllocationService.AutoAllocate();
            if (success) return Ok();
            else return BadRequest(msg);
        }

        public record AdjustRecord(Guid regId1, Guid regId2);
        // api/allocation/adjustAllocation
        [HttpPut("adjustAllocation")]
        public IActionResult AdjustAllocation([FromBody] AdjustRecord record)
        {
            var (success, msg) = allocationService.AdjustAllocation(record.regId1, record.regId2);
            if (success) return Ok();
            else return BadRequest(msg);

        }

        [HttpPost("test")]
        public IActionResult Test([FromBody] ExamRoomAllocation ExamRoomAllocation)
        {
            Console.WriteLine("*****"+ExamRoomAllocation.ExamRoomId);
            var (success, msg) = allocationService.AddAllocation(ExamRoomAllocation);
            if (success) return Ok();
            else return BadRequest(msg);
        }

        // api/allocation/export
        [HttpGet("export")]
        public IActionResult ExportToExcel()
        {
            MemoryStream stream = allocationService.GetExportFile();

            // 设置响应头，使浏览器将响应作为文件下载
            var content = new MemoryStream(stream.ToArray());
            var contentType = "application/vnd.ms-excel";
            var fileName = "data.xls";

            return File(content, contentType, fileName);
        }

        [HttpDelete("empty")]
        public IActionResult EmptyAllocations()
        {
            var (success, msg) = allocationService.EmptyAllocations();
            if (success) return Ok();
            else return BadRequest(msg);
        }

    }
}

// requestBody处理方法：
//AdjustRecord r = new AdjustRecord();
//AdjustRecord o = r with { name = "new" };
//String json = """
//    { 
//        "abc": 124,
//        "b": {
//          "c": [123]
//        }
//    }
//    """;
//JsonNode doc = JsonNode.Parse(json);
//var arr = doc["b"]["c"] as JsonArray;
//foreach (var item in arr)
//{
//    item.GetValue<Guid>();
//}